import {$post,$get,$delete} from '../utils/request.js'
export default {
	namespaced: true,
	state() {
		return {
			checkedIdx: -1,  // 记录用户勾选的地址
			addressList: [
				// {
				// 	username: 'ice',
				// 	phone:'15000000000',
				// 	city: '上海',
				// 	region: '黄埔区',
				// 	detail: '黄埔江畔',
				// 	isdefault: true
				// },
				// {
				// 	username: 'lick',
				// 	phone:'16000000000',
				// 	city: '上海',
				// 	region: '黄埔区',
				// 	detail: '黄埔江畔',
				// 	isdefault: false
				// },
				// {
				// 	username: 'jack',
				// 	phone:'17000000000',
				// 	city: '上海',
				// 	region: '黄埔区',
				// 	detail: '黄埔江畔',
				// 	isdefault: false
				// }
			]
		}
	},
	getters:{
		orderAddress(state) {
			// 订单中的地址
			let {checkedIdx,addressList} = state
			if(checkedIdx!=-1){
				return addressList[checkedIdx]
			}
			let len = addressList.length
			for(let i =0; i < len; i++) {
				if(addressList[i].isdefault) {
					return addressList[i]
				}
			}
		}
	},
	mutations: {
		addressDefaultMut(state,idx) {
			// 设为默认
			state.addressList.forEach((item,i) => {
				i==idx ? item.isdefault = true : item.isdefault = false
			})
		},
		addressCheckedMut(state,idx) {
			// 选取新地址
			state.checkedIdx = idx
			state.addressList.forEach((item,i) => {
				i==idx ? item.isdefault = true : item.isdefault = false
			})
			uni.navigateBack({
				delta: 1
			})
		},
		addressAddMut(state,addressObj) {
			state.addressList.push(addressObj)
		},
		addressInitMut(state,addressArr){
			// 初始化地址信息
			state.addressList = addressArr
		}
	},
	actions: {
		addressAddAct({commit},addressObj) {
			$post('/1.1/classes/address',addressObj).then(({objectId}) => {
				// console.log(res);
				commit('addressAddMut',{
					...addressObj,
					objectId
				})
				uni.navigateBack({
					delta: 1
				})
			}).catch(err => {
				console.log(err);
			})
		},
		addressInitAct({commit},userid) {
			let url = `/1.1/classes/address?where={"userid":"${userid}"}`
			$get(url).then(({results}) => {
				// console.log(11,res);
				commit('addressInitMut',results)
			}).catch(err => {
				console.log(err);
			})
		},
		deleteAddressAct({commit},objectId) {
			// console.log(this);
			$delete(`/1.1/classes/address/${objectId}`).then(res => {
				uni.showToast({
					title: '地址删除成功',
					icon: 'none'
				})
			}).catch(err => {
				console.log(err)
			})
		}
	}
}